package com.hwua.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hwua.entity.Book;
import com.hwua.util.BookUtil;

public class ShowAllBooksServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter out = resp.getWriter();//得到字符输出流
		out.write("热门图书列表:<br>");
		Map<String, Book> booksMap = BookUtil.findAllBooks();
		Set<Entry<String, Book>> entrys = booksMap.entrySet();
		for(Entry<String, Book> entry:entrys){
			Book book = entry.getValue();
			out.write("<a href='"+req.getContextPath()+"/showDetail?id="+book.getId()+"'>"+book.getName()+"</a><br>");
		}
		
		out.write("<hr>");
		out.write("浏览过的书:<br>");
		//读取cookie
		Cookie[] cookies = req.getCookies();
		if(cookies==null){
			out.write("没有浏览过图书:<br>");
		}else{
			for(Cookie cookie:cookies){
				if(cookie.getName().equals("histroyrecord")){
					String value=cookie.getValue();//得到拼接好的字符串
					String [] ids = value.split("-");
					for(String id:ids){
						out.write(BookUtil.findBookById(id).toString()+"<br>");
					}
				}
			}
		}
		
		out.close();
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}
}
